<template>
  <div id="app">
      <el-card shadow="always">
        {{userSearch}}
        <el-form :inline="true" size="medium" :model="userSearch" class="demo-form-inline">
          <el-form-item label="姓名">
            <el-input v-model="userSearch.name" placeholder="姓名"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="userSearch.sex" placeholder="性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" plain @click="openDiag" icon="el-icon-plus">添加用户</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" plain @click="handleDelete" icon="el-icon-remove">批量删除</el-button>
          </el-form-item>
        </el-form>
        <el-table
            :data="userList"
            style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              label="姓名"
              prop="name"
              align="center">
          </el-table-column>
          <el-table-column
              label="年龄"
              prop="age"
              align="center">
          </el-table-column>
          <el-table-column
              label="性别"
              prop="sex"
              align="center">
          </el-table-column>
          <el-table-column
              label="电话"
              prop="phone"
              align="center">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  @click="handleEdit(scope.row)">编辑</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index,scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <span class="demonstration">完整功能</span>
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </el-card>
    <el-dialog title="title"  :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      {{user}}
      <el-form :model="user" :rules="rules" ref="ruleForm">
        <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="user.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model="user.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
          <el-select v-model="user.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone" :label-width="formLabelWidth">
          <el-input v-model="user.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectType">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <span>你确定要删除用户吗？</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="open3">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
import userApi from "@/api/user"

export default {
  data() {
    var checkAge = (rule, value, callback) => {
      setTimeout(() => {
        const numericValue = Number(value);

        // 检查是否为有效数字
        if (isNaN(numericValue)) {
          callback(new Error('请输入数字值'));  // 如果不是数字，提示“请输入数字值”
        } else if (numericValue <= 0 || numericValue >= 150) {
          callback(new Error('请输入正确的年龄'));  // 如果年龄不在有效范围，提示“请输入正确的年龄”
        } else {
          callback();  // 验证通过
        }
      }, 1000);
    };
    return {
      userList: [],
      page: 1,
      pageSize:10,
      total:100,
      userSearch:{},//查询条件对象
      dialogFormVisible:false,  // 控制对话框的显示隐藏
      dialogVisible:false,
      formLabelWidth:'100px',   // 对话框提示文本的宽度
      user: {},              // 用户对象（添加或修改）
      title: '添加用户',          // 对话框标题
      type: '添加',
      multipleSelection: [],
      deleteIds:[],
      ruleForm: {
        name: '',
        age:null,
        sex: '',
        phone: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { validator: checkAge, trigger: 'blur'}
        ],
        sex: [
          {  required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入用户电话', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created: function () {
    this.search()
  },
  methods: {
    //1.查询所有用户
    async findUsers(){
      const {data:res} = await userApi.findAll()
      this.userList =res.data.users;
    },
    async findByPage(page, pageSize) {
      const {data:res} = await userApi.findByPage(page,pageSize)
      if (res.code === 200){
        this.userList =res.data.users.rows;
        this.total = res.data.users.total;
      }
    },
  open1() {
    this.saveUser()
    this.$message({
      message: '添加用户成功',
      type: 'success'
    });
},
  open2() {
    this.updateUser()
  this.$message({
    message: '修改用户成功',
    type: 'success'
  });
},
  open3() {
      this.deleteUser()
  this.$message({
    message: '删除用户成功',
    type: 'warning'
  });
},
    selectType(){
      if (this.type === '添加'){
       this.open1()
      }else if(this.type === '修改'){
        this.open2()
      }else if(this.type === '删除'){

      }
    },
  async search(){
    const {data:res} = await userApi.search(this.page,this.pageSize,this.userSearch)
    this.userList = res.data.users.rows
    this.total = res.data.users.total
  },
    opend(){
      this.type = '删除'
      this.title = '删除用户'
      this.dialogVisible = true
    },
    openDiag(){
      this.type = '添加'
      this.title = '添加用户'
      this.user = {}
      this.dialogFormVisible = true;
    },
  openDiagwithRow(row) {
    this.type = '修改'
    this.title = '修改用户'
    this.user = { ...row };
    this.dialogFormVisible = true;
  },
  async saveUser(){
    const {data:res} = await userApi.save(this.user)
    if (res.code === 200){
      // this.$message({
      //   type: 'success',
      //   message: res.message
      // })
      this.dialogFormVisible = false;
      this.search()
    }else {
      this.$message({
        type: 'error',
        message: res.message
      })
    }
  },
  async updateUser() {
    const {data:res} = await userApi.update(this.user)
    if (res.code === 200){
      // this.$message({
      //   type: 'success',
      //   message: res.message
      // })
      this.dialogFormVisible = false;
      this.search()
    }else {
      this.$message({
        type: 'error',
        message: res.message
      })
    }
  },
    async deleteUser(){
      const {data:res} = await userApi.delete(this.deleteIds)
      if (res.code === 200){
        // this.$message({
        //   type: 'success',
        //   message: res.message
        // })
        this.dialogVisible = false;
        this.search()
      }else {
        this.$message({
          type: 'error',
          message: res.message
        })
      }
    },
    handleEdit(row) {

      this.openDiagwithRow(row)
      console.log(row);
    },
    handleDelete(index,row) {
      this.deleteIds = []
      if (row) {
        this.deleteIds.push(row.id)
        console.log("row.id", row.id);
      }else{
        this.deleteIds = this.multipleSelection.map(m => m.id)
      }
      this.opend()
    },
    handleSizeChange(val) {
      this.pageSize = val
      // this.findByPage()
      this.search()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page = val
      // this.findByPage()
      this.search()
      console.log(`当前页: ${val}`);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
}

</script>
<style>
.el-card {
  width: 90%;
  margin: auto;
}
#app{display: flex;
  justify-content: center;
}
.el-pagination{
  text-align: right;
  margin-top: 15px;
}
</style>